package org.koyabr.webx.demo.danmaku.web.ajax.module.screen;

import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.citrus.turbine.Context;

import org.koyabr.webx.demo.danmaku.biz.PostManager;
import org.koyabr.webx.demo.danmaku.biz.UserManager;
import org.koyabr.webx.demo.danmaku.dal.dataobjs.Post;
import org.koyabr.webx.demo.danmaku.dal.dataobjs.User;
import org.koyabr.webx.demo.danmaku.web.common.DanmakuUser;
import org.koyabr.webx.demo.danmaku.web.common.util.ListTool;
import org.springframework.beans.factory.annotation.Autowired;

public class WatcherList {

	@Autowired
	private PostManager postManager;

	@Autowired
	private UserManager userManager;

	@Autowired
	private HttpServletRequest request;

	public void execute(Context context) throws Exception {
		String postId = request.getParameter("postId");
		Post post;
		if (postId == null || (post = postManager.getPostById(postId)) == null)
			return;

		String type = request.getParameter("type").toLowerCase();
		User currentUser = userManager.getUser(DanmakuUser.getCurrentUser()
				.getUsername());
		if (type != null && currentUser != null) {
			// 当前用户出入队列

			if ("add".equals(type)) {
				currentUser.watchSet.add(post);
			} else if ("remove".equals(type)) {
				currentUser.watchSet.remove(post);
			}

		}

		// 轮询观众列表
		LinkedList<List<User>> watcherList = (LinkedList<List<User>>) ListTool.splitList(post.watchSet
				.toList(), 6);

		context.put("watcherList", watcherList);
	}
}
